package com.jinlejia.erp.ui.home;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityHomePuzzleBinding;
import com.jinlejia.erp.ui.common.GuideDialog;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.ACache;
import com.jinlejia.erp.utils.DataFilter;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

import okhttp3.Call;

/**
 * 拼了（Activity）
 */

public class PuzzleActivity extends AppCompatActivity {
    private ProgressDialog progressDialog;
    private FileOutputStream out;

    private ActivityHomePuzzleBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_home_puzzle);
        binding.backBtn.setOnClickListener(v->finish());
        progressDialog = new ProgressDialog(this, "正在保存...");
        initView();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //指引弹出层
        if (TextUtils.isEmpty(ACache.get(this).getAsString("guide_puzzle")))
            new GuideDialog(this, "guide_puzzle", R.mipmap.guide_puzzle).show();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        getData();
        Glide.with(this).load(getIntent().getStringExtra("url")).into(binding.puzzlePicture);
        binding.editText.setCursorVisible(false);//隐藏光标
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        binding.editText.setOnClickListener(view -> binding.editText.setCursorVisible(true));
        binding.editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                binding.editText.setCursorVisible(false);
            }
        });
        binding.puzzleSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap bitmap = getViewBitmap(binding.puzzleScreenLayout);
                progressDialog.show();
                try {
                    SaveFile(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public static Bitmap getViewBitmap(View view) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }

    /**
     * 保存图片
     *
     * @param bitmap
     * @throws IOException
     */
    public void SaveFile(Bitmap bitmap) throws IOException {
        File appDir = new File(Environment.getExternalStorageDirectory(), "HousePicture");//在SD卡中创建一个文件夹
        if (!appDir.exists()) {//如果该文件夹不存在，则创建一个文件夹
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG,100, out);
        out.flush();
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        this.sendBroadcast(intent);//这个广播的目的就是更新图库，发了这个广播进入相册就可以找到你保存的图片了！，记得要传你更新的file哦

        share(file);
    }

    /**
     * 分享
     * @param file
     */
    private void share(File file) {
        if (file.exists()) {
            String path = file.getPath();
            Intent intent1 = new Intent(PuzzleActivity.this, PuzzleSaveActivity.class);
            intent1.putExtra("image", path);
            startActivity(intent1);
        }
    }

    /**
     * 获取数据
     */
    public void getData() {
        OkHttpUtils
                .get()
                .url(ApiConfig.PUZZLE)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(PuzzleActivity.this, response, null)) {
                            JSONObject object = JSON.parseObject(response.get("data").toString());
                            if (!TextUtils.isEmpty(object.get("imageUrl").toString())){
                                Picasso.with(PuzzleActivity.this).load(ApiConfig.MAGEHEADER_URL().concat(object.get("imageUrl").toString())).placeholder(R.mipmap.ic_role_head).into(binding.userHead);
                            }else {
                                binding.userHead.setImageResource(R.mipmap.ic_role_head);
                            }
                            binding.name.setText(object.get("name").toString());
                            binding.phoneNumber.setText(object.get("tel").toString());
                            binding.address.setText(object.get("deptName").toString());
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
